package top.atluofu.admin.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;

/**
 * @ClassName: JwtHelper
 * @description: TODO
 * @author: 有罗敷的马同学
 * @datetime: 2023Year-05Month-11Day-0:21
 * @Version: 1.0
 */
public class JwtHelper {

    // 令牌过期时间
    private static long tokenExpiration = 365L * 24 * 60 * 60 * 1000;

    // 加密的key
    private static Key key = Keys.hmacShaKeyFor("abcdefghijklmnopqrstuvwxyzasdfasdfsadfasdfasdf".getBytes());

    public static String createToken(Long userId, String userName) {
        return Jwts.builder()
                .setSubject("P2P-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("userName", userName)
                .signWith(key)
                .compact();
    }

    public static Long getUserId(String token) {
        try {
            if (token == null) return null;

            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            String userId = claims.get("userId").toString();
            return Long.parseLong(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getUserName(String token) {
        try {
            if (token == null) return null;

            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("userName");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
